import React, {Component, PureComponent} from 'react';

import {message, Spin, Modal, Button, Radio, Badge, Form, Checkbox, Input} from 'antd';
import {connect} from 'dva';
import {router, Link} from 'umi';
import styles from './index.less';
import {getStorage, removeStorage, setStorage, urlEncode, pswSha1, getRandomKey} from 'jh-utils';
import {isEmpty, pick, isFunction} from 'lodash-es';
import {formatMsgByCn, myFormatMessage} from '@/utils/localeUtils';
import {GlobalProvider, SelectLang, ObjectSelect, jhError} from 'jh-lib';
import {LockOutlined, UserOutlined, GlobalOutlined} from "@ant-design/icons";
import {STORAGE_KEY} from "@/globalConfig";
import trim from "lodash-es/trim";
import {objectBoxFetch} from "@/pages/User/Login/service";


export default class LoginPage extends PureComponent {

  defaultLogin = false;
  openid = '';

  constructor(props) {
    super(props);
    const state = {
      type: 'tab1',
      autoLogin: true,
      spinning: false,
      logining: false,
      values: {},
      boxValues: {},
    };
    // 如果url上带有参数，表示是静默的登录
    const {location} = this.props;

    if (location && !isEmpty(location.query) && 'y' === location.query.defaultLogin) {
      this.defaultLogin = true;
      state.spinning = true;
      this.openid = location.query.openid;

      if (location.query.phone) { // 手机登录
        state.values = pick(location.query, ['phone', 'captcha', 'Auth']);
        state.type = 'tab2';

      } else if (location.query.values) { // 账号密码登录

        try {
          state.values = JSON.parse(location.query.values);

        } catch (e) {
        }
      }

    }
    this.state = state;
  }

  componentDidMount() {
    const {location} = this.props;

    // 静默登录
    if (this.defaultLogin) {
      if (this.state.values.username && this.state.values.password) {
        this.pwdLogin(this.state.values, false);
      }
    }
  }

  // onSubmit = async () => {
  //   const $this = this;
  //
  //   // let period = $this.state.period
  //   // console.log('》》》》》',period)
  //   // if(isEmpty(period)){
  //   //   message.error('会计期间不能为空');
  //   //   return false
  //   // }
  //   if ('tab1' === this.state.type) { // 账号密码
  //
  //     // 判断是否子丶主公司
  //     // if ($this.state.isRoot) {
  //     //   let isOk = await this.checkDomain(this.state.host);
  //     //   if (!isOk) {
  //     //     return false;
  //     //   }
  //     // }
  //     // 如果是账号密码登录，用 this.loginFrom
  //     const {validateFields} = this.loginFrom;
  //     validateFields((err, values) => {
  //       if (!err) {
  //         $this.setState({spinning: true}, () => {
  //           // 登录
  //           this.pwdLogin(values);
  //         });
  //       }
  //     });
  //   } else {
  //     // 如果是手机号登录，用 this.pros.form
  //     // const {validateFields} = this.props.form;
  //     // console.log(`登录时候是手机号登录`);
  //     // validateFields((err, values) => {
  //     //   if (!err) {
  //     //     $this.setState({spinning: true, values: values}, () => {
  //     //       // 查询公司信息，获取域名
  //     //       $this.findUserCorps(values);
  //     //     });
  //     //   }
  //     // });
  //   }
  // };

  onFinish = (values) => {
    const $this = this;
    console.log('Received values of form: ', values);
    // 登录
    this.pwdLogin(values);
  };

  /**
   * 用户名密码登录
   * @param values
   * @param needSha1
   */
  pwdLogin(values, needSha1 = true) {
    const $this = this;
    const {dispatch} = this.props;
    let boxValues = $this.state.boxValues || {};

    if (isEmpty(boxValues)) {
      jhError({
        title: myFormatMessage('comp.form.select.required', {name: formatMsgByCn('公司')})
      });
      return false;
    }

    if (dispatch) {
      let {password} = values;
      let username = trim(values.username);

      if (needSha1) {
        password = pswSha1({username, password});
      }

      this.setState({logining: true}, () => {
        const dispatchReturn = dispatch({
          type: 'global/pswLogin',
          payload: {username, password, corp: boxValues.code}
        });

        if (dispatchReturn instanceof Promise) {
          dispatchReturn.then($this._afterLogin.bind($this));
        } else {
          $this._afterLogin({});
        }

      });
    }
  }

  _afterLogin(rsp) {
    const {dispatch} = this.props;
    if (rsp && 200 === rsp.status) {
      message.success(formatMsgByCn('登录成功'), 1);
      let timeoutRoute = getStorage(STORAGE_KEY.TIMEOUT_ROUTE); // 登录过期前访问的页面路由
      removeStorage(STORAGE_KEY.TIMEOUT_ROUTE);
      removeStorage(STORAGE_KEY.SHOWING_TIMEOUT); // 这是用来避免重复弹出[登录过期提示框]的，登录成功后也要清空

      //获取当前用户的站点、部门
      dispatch({
        type: 'global/findCurrentUserInfo',
        payload: {}
      })
      // 如果是在 iframe 里，则关闭当前登录 iframe 弹框
      if (window.isIframe) {
        // removeStorage(STORAGE_KEY.IFRAME_LOGIN);
        // 通过调用父窗口的 dealAfterLogin 方法，传当前的登录数据过去，以处理父窗口的登录状态
        if (isFunction(window.parent.dealAfterLogin)) {
          window.parent.dealAfterLogin(rsp);
        }

      } else {
        // window.location.replace(`${window.location.protocol}//${domainName}/${window.location.pathname}#/`);
        router.replace(timeoutRoute || '/');
      }
    } else {

      this.setState({spinning: false, logining: false}, () => {

        if (this.defaultLogin) {
          this.defaultLogin = false;

          if (this.openid) {
            router.replace('/user/authorLogin');
          } else {
            router.replace('/user/login');
          }

        }
      });

    }
  }

  // onTabChange = (key: string) => {
  //   this.setState({
  //     type: key,
  //   });
  // };

  // changeAutoLogin = e => {
  //   this.setState({
  //     autoLogin: e.target.checked,
  //   });
  // };

  render() {
    if (this.defaultLogin) {
      return <Spin spinning={true} size={'large'} style={{display: 'block', margin: '100px auto'}}/>;
    }

    // 标识是不是在 “iframe"里面
    // 如果在 iframe 里，不显示 “域名输入框” 和 *注册账户*
    // let isIframe = 'LOGIN' === getStorage(STORAGE_KEY.IFRAME_LOGIN);
    // let isIframe = window.isIframe;
    let SHOWING_TIMEOUT = getStorage("SHOWING_TIMEOUT");
    let {boxValues} = this.state;
    return (
      <div className={styles.main}>

        <h3 className={'fwb f16 text-center mb16'}>{formatMsgByCn('请先登录')}</h3>
        <div className={'mb8 text-right'}>
          <SelectLang btnJsx={(
            <span style={{cursor: 'pointer'}}>
                        <GlobalOutlined className={'text-primary'}/> {formatMsgByCn('切换语言')}
                      </span>
          )}/>
        </div>
        {/*<div className={styles.crop}>*/}
        {/*  */}

        {/*</div>*/}
        <Form.Item>
          <ObjectSelect
            needMenu={false}
            fetchList={({inputVal}) => {
              console.log('fetchList value', inputVal);
              objectBoxFetch({searchText: inputVal}).then((rsp) => {
                if (rsp && 200 === rsp.status) {
                  this.corpList = rsp.data || [];
                  this.setState({randomKey: getRandomKey()})
                }
              })
            }}
            compData={this.corpList}
            value={boxValues}
            onChange={(values) => {
              console.log(">>>>", values);
              this.setState({boxValues: values})
            }}
          />
        </Form.Item>
        <Form
          name="normal_login"
          className="login-form"
          initialValues={{remember: true}}
          onFinish={this.onFinish}
        >
          <Form.Item
            name="username"
            rules={[{required: true, message: formatMsgByCn('请输入{name}', {name: '账号'})}]}
          >
            <Input
              size={"large"}
              prefix={<UserOutlined className="site-form-item-icon"/>}
              placeholder={myFormatMessage('field.account')}/>
          </Form.Item>
          <Form.Item
            name="password"
            rules={[{required: true, message: formatMsgByCn('请输入{name}', {name: '密码'})}]}
          >
            <Input.Password
              size={"large"}
              prefix={<LockOutlined className="site-form-item-icon"/>}
              placeholder={myFormatMessage('field.psw')}
            />
          </Form.Item>
          <Form.Item>
            <Form.Item name="remember" valuePropName="checked" noStyle>
              <Checkbox>{myFormatMessage('info.remember')}</Checkbox>
            </Form.Item>

            {/*<Link className={styles.forgot} to={'/'}>{myFormatMessage('info.forget.psw')}</Link>*/}
          </Form.Item>

          <Form.Item>
            <Button type={"primary"} size="large"
                    htmlType="submit"
                    block={true}
                    loading={this.state.spinning || this.state.logining}>{formatMsgByCn('登录')}</Button>
          </Form.Item>
        </Form>

      </div>
    );
  }

}
